package com.sensorviewera;

import android.hardware.SensorEvent;
/*本类对获得传感器数据进行预处理*/
public class SensorData
{
    public SensorData(String name){pack_head=name.getBytes();}

    private byte[] pack_head;
    private int timestamp=0;
    private int timer=0;
    private int feq=25;
    private static final int ts=20;
    public void setFeq(int feq_){feq=feq_;}
    public void reset(){timestamp=0;timer=0;}
    public byte[] getAccData(SensorEvent sensorEvent)
    {
        timestamp+=ts;
        switch (feq)
        {
            case 0:
                break;
            case 5: 
                if(++timer<10)
                    return null;
                break;
            case 10:
                if(++timer<5)
                    return null;
                break;
            case 25:
                if(++timer<2)
                    return null;
                break;
            case 50:
                break;
            default:
                return null;
        }
        timer=0;
        int value_count=sensorEvent.values.length;
        int pack_size=16+value_count*4;
        byte[] buffer =new byte[pack_size];
        System.arraycopy(pack_head,0,buffer,0,4); 
        System.arraycopy(intToBytes(pack_size),0,buffer,4,4);
        System.arraycopy(intToBytes(feq),0,buffer,8,4);
        System.arraycopy(intToBytes(timestamp),0,buffer,12,4);
        for(int i=0;i<value_count;i++) 
            System.arraycopy(floatToBytes(sensorEvent.values[i]),0,buffer,16+i*4,4);
        return buffer;
    }
    private byte[] floatToBytes(float data)
    {
        int tmp=Float.floatToIntBits(data);
        byte[] bytes = new byte[4];
        bytes[0] = (byte) (tmp & 0xff);
        bytes[1] = (byte) ((tmp & 0xff00) >> 8);
        bytes[2] = (byte) ((tmp & 0xff0000) >> 16);
        bytes[3] = (byte) ((tmp & 0xff000000) >> 24);
        return bytes;
    }
    private byte[] intToBytes(int tmp)
    {
        byte[] bytes = new byte[4];
        bytes[0] = (byte) (tmp & 0xff);
        bytes[1] = (byte) ((tmp & 0xff00) >> 8);
        bytes[2] = (byte) ((tmp & 0xff0000) >> 16);
        bytes[3] = (byte) ((tmp & 0xff000000) >> 24);
        return bytes;
    }
}

